package 四数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int length = nums.length;
        for(int i = 0;i < length - 3;){
            for(int j = i + 1;j < length - 2;){
                int left = j + 1;
                int right = length - 1;
                long flg = (long)target - nums[i] - nums[j];
                while (left < right){
                    List<Integer> list = new ArrayList<>();
                    int sum = nums[left] + nums[right];
                    if(sum > flg){
                        right--;
                    }else if(sum < flg){
                        left++;
                    }else{
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        ret.add(list);
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]){
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]){
                            right--;
                        }
                    }
                }
                j++;
                while(j < length - 2 && nums[j] == nums[j - 1]){
                    j++;
                }
            }
            i++;
            while (i < length - 3 && nums[i] == nums[i - 1]){
                i++;
            }
        }
        return ret;
    }
}